<template>
  <div class="flex-column textUpload">
    <el-upload ref="textUploadRef" v-show="value.length < fileLength" class="upload-demo" :accept="accept"
      :auto-upload="false" action="#" :multiple="multiple" :show-file-list="false" :before-upload="beforeAvatarUpload"
      :on-change="onChange">
      <el-button type="primary">选择文件</el-button>
    </el-upload>
    <div v-for="(item, key) in value" :key="key" class="flex-justify-between textContent">
      <div class="flex-start flex1">
        <el-icon style="margin-right: 6px;">
          <Document />
        </el-icon>
        <div class="content">{{ item.name }}</div>
      </div>
      <el-icon style="cursor: pointer;" @click="(row) => handleRemove(row, key)">
        <Close />
      </el-icon>
    </div>
  </div>
</template>
<script setup lang="ts">
import {
  getCurrentInstance,
  ref
} from 'vue';

import { ElMessage } from 'element-plus';

const { proxy } = <any>getCurrentInstance();
const textUploadRef = ref(null)
const { value, multiple, limitSize, accept, fileLength } = defineProps({
  value: {
    type: Array,
    default: () => []
  },
  multiple: {//多选
    type: Boolean,
    default: false
  },
  fileLength: {
    default: 20,
    type: Number,
  },
  limitSize: {
    // 文件大小
    default: 10,
    type: [Number, String],
  },
  accept: {
    type: String,
    default: '.mp4,.mov,.wmv,.flv,.mpeg,.mpeg,.webm,.avi,.avi,.3GP'
  }
})
function handleRemove(row, key) {//移除文件
  proxy.value.splice(key, 1)
}
function beforeAvatarUpload(file) {//
  const isLt2M = file.size / 1024 / 1024 < parseInt(limitSize);
  if (!isLt2M) {
    ElMessage.error(`上传文件大小不能超过 ${limitSize}MB!`);
    return false;
  }
  return isLt2M;
}
function onChange(val) {
  if (fileLength === 1) {
    proxy.value.push(val.raw)
    if (value.length < fileLength) {
      proxy.value.push(JSON.parse(JSON.stringify(val.raw)))
    }
  }
}
</script>
<style lang="scss" scoped>
.textUpload {
  width: 100%;

  .textContent {
    width: 100%;
    overflow: hidden;
    box-sizing: border-box;
    margin-top: 10px;
    padding: 0px 10px;
    border-radius: 4px;
    height: 30px;
    color: #606266;
    cursor: pointer;

    &:hover {
      background-color: #f7f6f6;
      color: var(--el-color-primary);
    }

    .content {
      width: 260px;
      overflow: hidden;
      /* 确保超出的内容被裁剪 */
      white-space: nowrap;
      /* 确保文本在一行内显示 */
      text-overflow: ellipsis;
      /* 使用沈略号表示文本被裁剪 */
    }
  }
}
</style>